<script setup lang="ts">
import { DeleteEnterprise, DeleteEnterpriseRent, getParkEnterprise, GetParkRentListAPI, GetRentListAPI, PostParkEnterpriseRentAPI, PostUploadAPI, PutExitRent } from '@/apis/park';
import type { EnterPriseData, GetParkEnterpriseParams, GetRentList, GetRentListInterface, PostParkEnterpriseRentParams } from '@/types/park';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
import { ref, watch } from 'vue';
import { CircleCheck ,Upload} from '@element-plus/icons-vue'
import router from '@/router';



const Datalist = ref<EnterPriseData[]>([])

const total = ref(0)

const params = ref<GetParkEnterpriseParams>({
  name:'', //企业名称
  page:1,
  pageSize:10,
})

// 搜索功能
const onSearch = () =>{
  // 首先将页码重置为1
  params.value.page = 1
  getData()
}

// 前端自定义的类型，用于显示嵌套表格
  interface EnterpriseWithRent extends EnterPriseData{
    // 合同列表
    rentList:GetRentListInterface[]
  }
  // 表格数据
  const exterpriseList = ref<EnterpriseWithRent[]>([])

  // 初始化时增加合同数据默认列表
  
// 获取企业列表
const getData = async () =>{
  const res = await getParkEnterprise(params.value)
  console.log('获取企业列表',res)
  Datalist.value = res.data.rows
  total.value = res.data.total
  // map 映射数据用于前端展示
  exterpriseList.value = res.data.rows.map((item)=>({
    ...item,
    rentList:[]  //合同列表默认值，用于嵌套表格渲染
  }))
}
getData()


  // 展开行数据
 const getRentList = async(row:EnterpriseWithRent) =>{
  // 根据企业id 获取合同列表
  const res = await GetParkRentListAPI(row.id)
  console.log('获取合同列表',res)
  // 把合同列表信息添加到企业信息中去
    row.rentList = res.data
 }



// 删除企业
const onDel = async (id:string) =>{
  try{

    // 二次确认操作
    ElMessageBox.confirm(
     '是否确认删除当前企业',
     'warning',  
    {
      confirmButtonText:'确认',
      cancelButtonText:'取消',
      type:'warning'
    })
    .then( async()=>{
    const res = await DeleteEnterprise(id)
    console.log('删除企业',res)
   //  删除完成之后再次获取
     ElMessage.success('删除成功')
     getData()
    })
        
  }catch(err){
    console.log(err)
  }

  
}

// 添加合同
const openDialog = ref(false)



// 上传前
const beforeUpload = (rawFile:UploadRawFile) =>{
  // 文件上传之前校验文件大小
  const allowSize = 5 * 1024 * 1024
  // 校验文件大小
  if(rawFile.size > allowSize){
    ElMessage.error('文件过大，请重新上传 5M 以下的文件')
      return false
  }
  return true
}
//文件上传
const onUploadRequest = async (options:UploadRequestOptions) =>{
  // 1. 准备 formData 对象
    const fd = new FormData()
  // 2.上传文件对象 
   fd.append('file',options.file)
 // 文件对象
// 租赁合同附件 contract
  fd.append('type','contract')
  // 3.调用接口上传文件
    const res = await PostUploadAPI(fd)
  // 4.保存合同附件 url 和 id 用来添加合同
  RentForm.value.contractId = res.data.id
  RentForm.value.contractUrl = res.data.url
  // 5.主动触发校验，如果校验通过 会清除错误信息
  addFormRef.value?.validateField('contractUrl')

  // 6. return 后端返回的数据 保存到response 中
   return res.data
}
// 销毁前
const removeUpload = () =>{
  // 清除数据
  RentForm.value.contractUrl = ''
  RentForm.value.buildingId = undefined
  // 主动触发校验
  addFormRef.value?.validateField('contractUrl')
}

const fileList = ref<UploadUserFile[]>([])

//每次关闭弹窗，清空表单
const cancel = () =>{
  openDialog.value = false
  addFormRef.value?.resetFields()
  cardDataArr.value = []
  fileList.value = []
  RentForm.value = initRentForm()
}

const addFormRef = ref<FormInstance>()
const onOk = async () =>{
  // 等待进行表单校验
   await addFormRef.value?.validate()
    try{
      // 校验通过发送请求
     const res = await PostParkEnterpriseRentAPI(RentForm.value)
     console.log('添加合同',res)
      // 添加完成之后，重新获取该企业最新的合同列表
      const enterpriseId = RentForm.value.enterpriseId
      if(enterpriseId){
        // 1.根据id ，重新获取该企业最新的合同列表
        const Rentres = await GetParkRentListAPI(String(enterpriseId))
        // 2.找到该企业对应的企业行
        const targetEngterprise = exterpriseList.value.find(item => item.id == String(enterpriseId));
        if(targetEngterprise){
          // 3.更新该企业的rentlist（响应式更新，界面会立即刷新）
          targetEngterprise.rentList = Rentres.data
        }
      }
    ElMessage.success('添加成功')
      // 添加完成之后重置表单
        cancel()
    }catch(err){
      console.log(err)
    }
}

// 表单默认数据，每次调用，都返回一个新对象
const initRentForm = () =>{
  return {
      buildingId:undefined,
      contractId:undefined,
      contractUrl: '',
      endTime:'',
      enterpriseId:undefined,
      startTime:'',
      type:undefined
  }
} 
// 添加合同 表单数据
const RentForm = ref<PostParkEnterpriseRentParams>(initRentForm())
// 表单校验规则
const addFormRules = ref<FormRules<PostParkEnterpriseRentParams>> ({
  buildingId:[{required:true,message:'请选择楼宇',trigger:'change'}],
  endTime:[{required:true,message:'请选择租赁日期',trigger:'blur'}],
  contractUrl:[{required:true,message:'请上传租赁合同',trigger:'blur'}]
})



// 时间选择器，监听时间的变化
// 日期数组
const cardDataArr = ref<string[]>([])
watch(cardDataArr,(val)=>{
  if(val){
    RentForm.value.startTime = val[0]
    RentForm.value.endTime = val[1]
    // console.log('数组发生变化啦~',val)
  }else{
      RentForm.value.startTime = ''
    RentForm.value.endTime = ''
  }
  //深度监听
},{deep:true}
)

// 通过disable Date函数 设置禁用掉的日期
const disableDate = ( time:Date ) =>{
  // 不能小于今日日期，包含今天 ( 1000 * 60 * 60 * 24 ->1天的毫秒数)
  return time.getTime() < Date.now()  
}

  // 查询可租赁楼宇
const RentList = ref<GetRentList[]>([])
// 添加合同
const  addRent = (id:number) =>{
  openDialog.value = true
  RentForm.value.type = 0 

const getRentList = async() =>{
    const res = await GetRentListAPI()
    console.log('查询可租赁楼宇',res)
    RentList.value = res.data
}

getRentList()
// 保存企业id 用于添加合同
  RentForm.value.enterpriseId = id
}
 
// 退出租赁合同
const ExitRent = async (row:GetRentListInterface) =>{
  try{
    // 二次确认操作
    ElMessageBox.confirm(
      '退租后不可撤回，是否退租当前楼宇',
      {
        confirmButtonText:'确认',
        cancelButtonText:'取消',
        type:"warning"
      }).then( async ()=>{
        const res = await PutExitRent(row.id)
          console.log('退出租赁合同',res)
          // 禁用按钮
          row.status = 3
          ElMessage.success('退租成功')
      })


  }catch(err){
    console.log(err)
  }

}

// 弹窗关闭时的回调
const onClose = () =>{
  console.log('弹窗关闭啦')
  // 关闭弹窗时 清空数据
  // 清空表单数据
  addFormRef.value?.resetFields()
  // 清空日期数组
  cardDataArr.value = []
  // 清空文件上传
  fileList.value = []
  // 
  RentForm.value = initRentForm()
  
}


// 删除租赁合同
const DelRent = async (row:EnterpriseWithRent, enterpriseId: string) =>{
  ElMessageBox.confirm(
    '删除后不可恢复，确定要删除租赁合同吗？',
    {
      confirmButtonText:'确认',
      cancelButtonText:'取消',
      type:'warning'
    }).then( async()=>{
    const res = await DeleteEnterpriseRent(row.id)
    console.log('删除租赁合同',res)
    ElMessage.success('删除成功')
    // 删除之后重新获取该企业最新的合同列表
      const rowId = row.id
      console.log('enterpriseId',enterpriseId)
      if(rowId){
        // 1.根据id 获取 最新的合同列表
        const Rentres = await GetParkRentListAPI(enterpriseId)

        // 2.找到该企业对应的企业行
        const targetEnterprise = exterpriseList.value.find(item => item.id == enterpriseId)
        if(targetEnterprise){
          // 3.更新该企业的rentList 刷新页面
          targetEnterprise.rentList = Rentres.data
        }
      } 
    })
}

// 查看企业详情
const goSee = (id:string) =>{
  router.push(`enterprise/detail/${id}`)
}
</script>
<template>
  <div class="park-enterprise-page">
    <!-- 搜索区域 -->
     <div class="Search-area">
        <text style="line-height: 30px;" >企业名称：</text>
        <el-input placeholder="请输入企业名称" clearable v-model="params.name" class="main-input" ></el-input>
        <el-button type="primary" @click="onSearch" >查询</el-button>
      </div>
      <!-- 分割线 -->
       <el-divider ></el-divider>
       <el-button  type="primary" @click="$router.push('/exterpriseAdd')" >添加企业</el-button>

       <!-- 表格区域 -->
        <el-table   @expand-change="getRentList" row-key="id" :header-cell-style="{ background: '#f4f6f8' }"
        style="height: 100%; margin-top: 20px; " :data="exterpriseList" >
        <el-table-column type="expand" >
          <template v-slot="{row}">
            <el-table :data="row.rentList"  :header-cell-style="{ background: '#e8f7ff' }" 
            style="margin: -8px 0px 0px 0px; "
            >
              <el-table-column label="租赁楼宇" width="300px" align="center" >
                <template #default="scope">
                  {{ scope.row.buildingName }}
                </template>
              </el-table-column>
              <el-table-column label="租赁起始时间"  width="330px" align="center">
                <template #default="scope">
                  {{ scope.row.startTime }} 至 {{ scope.row.endTime  }}
                </template>
              </el-table-column>
              <el-table-column label="合同状态"  width="330px"  align="center" >
                <template #default="scope">
                   <el-tag  v-if="scope.row.status === 0 " color="#e8f7ff" type="primary">待生效</el-tag>
                   <el-tag  v-if="scope.row.status === 1 " type="success">生效中</el-tag>
                   <el-tag  v-if="scope.row.status === 2 " type="info">已到期</el-tag>
                   <el-tag  v-if="scope.row.status === 3 " type="danger">已退租</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="390px" >
                <template #default="scope"> 
                  <el-button size="small" type="text">续租</el-button>
                  <el-button size="small" type="text" :disabled="scope.row.status === 3 " @click="ExitRent(scope.row)">退租</el-button>
                  <el-button size="small" type="text" :disabled="scope.row.status !== 3 " @click="DelRent(scope.row,row.id)">删除</el-button>
                </template >
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
          <el-table-column  type="index" label="序号" width="160px" ></el-table-column>
          <el-table-column  prop="name" label="企业名称" width="280px"></el-table-column>
          <el-table-column  prop="contact"  label="联系人" width="220px"></el-table-column>
          <el-table-column  prop="contactNumber" label="联系电话" width="240px"></el-table-column>
          <el-table-column  label="操作" width="400px">
            <template #default="{row}">
              <el-button size="small" type="text" @click="addRent(row.id)">添加合同</el-button>
              <el-button size="small" type="text" @click="goSee(row.id)">查看</el-button>
              <el-button size="small" type="text" @click="$router.push(`/exterpriseAdd/${row.id}`)">编辑</el-button>
              <el-button size="small" type="text" @click="onDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style=" margin-top: 25px;position: fixed;right: 30px;">
          <el-pagination layout="total,prev,pager,next,sizes" 
          :total="total" :page-sizes="[2,5,10,20,100]"  v-model:current-page="params.page"
          v-model:page-size="params.pageSize" @change="getData()"
          ></el-pagination>
        </div>
        <!-- 添加合同弹窗 -->
         <el-dialog @close="onClose" v-model="openDialog" :modal="true" width="600px" >
            <template #header>添加合同</template>
          <template #default>
            <div class="addRentDiv">
              <el-form ref="addFormRef" 
              :rules="addFormRules" label-width="80px" label-position="top" :model="RentForm"> 
                <el-form-item label="租赁楼宇" prop="buildingId">
                    <el-select v-model="RentForm.buildingId"  placeholder="请选择要租赁的楼宇" style="width: 90%;" clearable>
                    <el-option
                        v-for="item in RentList" 
                        :key="item.id"
                        :value="item.id"
                        :label="item.name"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item  style="width: 90%;" label="租赁起止日期" prop="endTime" >
                  <el-date-picker 
                  v-model="cardDataArr"
                  type="datetimerange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  range-separator="至"
                  format="YYYY-MM-DD HH:mm"
                  date-format="YYYY/MM/DD ddd"
                  time-format="A hh:mm:ss"
                  :disabled-date="disableDate"
              />
                </el-form-item>
                <el-form-item label="租赁合同 " prop="contractUrl">
                    <el-upload
                        class="upload-demo"
                        action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                        multiple
                        :limit="1"
                        v-model:file-list="fileList"
                        :http-request="onUploadRequest"
                        accept=".doc,.docx,.pdf"
                        :before-upload="beforeUpload"
                        :on-remove ="removeUpload"
                      >
                        <el-button  v-if="fileList.length == 0" type="primary" plain :icon="Upload">上传文件</el-button>
                        <el-button v-else type="success" :icon="CircleCheck" disabled>已上传</el-button>
                        <template #tip>
                          <div class="el-upload__tip">
                          支持 .doc .docx .pdf格式，文件大小不超过 5MB。
                          </div>
                        </template>
                      </el-upload>
                </el-form-item>
              </el-form>
            </div>
          </template>
          <template #footer>
            <div style="background-color: #f4f6f8; height: 60px;margin: -15px;" >
                <el-button  @click="cancel" style="margin-top: 15px;padding: 17px;">取消</el-button>
              <el-button type="primary" @click="onOk" style="padding: 15.5px;margin-top: 15px; margin-right: 15px;">确定</el-button>
            </div>
          </template>
         </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.addRentDiv{
  height: 320px;
  border-radius: 20px;
  margin: 30px;
}


.main-input{
  width: 220px;
  margin-right: 20px;
}
.Search-area{
  display: flex;
  
}
.park-enterprise-page{
  padding: 20px;
}
</style>
